/**
 * @Author xiaoge
 * @Date 20240517
 * Describe:开启线程获取定位数据
 * 开线程获取定位数据,开线程执行计算量大的操作,避免阻塞主线程
 */
import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';

var workerPort: ThreadWorkerGlobalScope = worker.workerPort;
import { LocationModel } from '../models/LocationModel'
import { IndicatorTypeEnum } from '../models/IndicatorTypeEnum'
import geoLocationManager from '@ohos.geoLocationManager';

// //初始化定位对象
let locationModelList: LocationModel[] = []
//定位的定时器
let timerLocation: number = -1 //计时器
workerPort.onmessage = function (e: MessageEvents) {
  //开始获取定位
  timerLocation = setInterval(async () => {
    //原生系统获取当前定位的信息
    const result = await geoLocationManager.getCurrentLocation()
    let model: LocationModel = new LocationModel()
    model.longitude = result.longitude
    model.latitude = result.latitude
    locationModelList.push(model)
    console.log('获取定位数据'+JSON.stringify(model))
    console.log('获取定位数组的长度'+JSON.stringify(locationModelList.length))
  }, 1000)
  //这里为了方便测试,定的是1秒钟获一次定位数据,可以自行修改 1000*60*5 5分钟

  //获取主线程传递过来的数据
  if (e.data ===IndicatorTypeEnum.STOP_LOCATION) {
    //销毁计时器
    clearInterval(timerLocation)
    //回传消息
    console.log('获取定位停止后数据'+JSON.stringify(locationModelList.length))
    workerPort.postMessage(locationModelList)
  }
}


workerPort.onmessageerror = function (e: MessageEvents) {
}


workerPort.onerror = function (e: ErrorEvent) {
}